/**
 * 
 */

package com.haiyi.software.app;

import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.haiyi.software.app.basic.FragmentBasicNearby;
import com.haiyi.software.entity.UserFriend;
import com.haiyi.software.tools.L;
import com.haiyi.software.tools.MyTools;
import com.haiyi.software.xmpp.event.XMPPConnectionState;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnPullEventListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.State;
import com.handmark.pulltorefresh.library.PullToRefreshListDelegate;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshListView.PullToRefreshListAdapter;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

/**
 * @author Administrator
 * 
 */
public class FragmentNearby extends FragmentBasicNearby implements
		PullToRefreshListDelegate {

	private final String TAG = "FragmentNearby";

	public final static int SHOW_ACTIVITY_SEARCH = 1;

	private PullToRefreshListView mPullRefreshListView;

	private DisplayImageOptions options;

	private ImageLoader imageLoader;

	private View view;

	private MyTools tools = MyTools.getInstance();

	private Button btn_search;

	private ImageView img_animation;

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		MainApplication.getInstance().getmXMPPConnEvent().clear();

		MainApplication.getInstance().getmXMPPConnEvent().add(this);

		view = inflater.inflate(R.layout.fragment_nearby, null);

		initComp();

		handler.sendEmptyMessageDelayed(1, 500);

		return view;

	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {

			mPullRefreshListView.setRefreshing();
		};
	};

	private void initComp() {

		this.img_animation = (ImageView) view.findViewById(R.id.img_animation);

		this.img_animation.setBackgroundResource(R.drawable.animation_eye_list);

		AnimationDrawable drawable = (AnimationDrawable) this.img_animation
				.getBackground();

		drawable.start();

		this.btn_search = (Button) view.findViewById(R.id.btn_search);
		this.btn_search.setOnClickListener(btnClick);
		// 图片控件
		imageLoader = ImageLoader.getInstance();
		options = new DisplayImageOptions.Builder()
				.imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
				.showImageOnLoading(R.drawable.ic_launcher)
				.showImageForEmptyUri(R.drawable.ic_launcher)
				.showImageOnFail(R.drawable.ic_launcher).cacheInMemory(true)
				.cacheOnDisc(true).considerExifParams(true)
				.displayer(new RoundedBitmapDisplayer(20)).build();
		// listview
		mPullRefreshListView = (PullToRefreshListView) view
				.findViewById(R.id.pull_refresh_list_nearby);

		mPullRefreshListView.setScrollingWhileRefreshingEnabled(false);
		mPullRefreshListView.setMode(Mode.BOTH);
		mPullRefreshListView.setScrollingWhileRefreshingEnabled(true);
		mPullRefreshListView.setPullToRefreshOverScrollEnabled(false);
		// Set a listener to be invoked when the list should be refreshed.
		mPullRefreshListView
				.setOnRefreshListener(new OnRefreshListener<ListView>() {

					@Override
					public void onRefresh(
							PullToRefreshBase<ListView> refreshView) {

						L.i(TAG, page + ":page");
						L.i(TAG, pagetotal + ":pagetotal");

						if (refreshView.isHeaderShown()) {
							page = 1;
							list.clear();
							requestNetworkData();
						} else {

							page++;
							if (page <= pagetotal) {
								requestNetworkData();
							} else {

								Log.i(TAG, page + ":" + pagetotal);
								handler2.sendEmptyMessageDelayed(1, 500);
								return;
							}

						}

					}
				});

		// Add an end-of-list listener
		mPullRefreshListView
				.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {

					@Override
					public void onLastItemVisible() {

					}
				});

		mPullRefreshListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				// TODO 自动生成的方法存根
				Intent chatIntent = new Intent(getActivity(), HiChat.class);

				UserFriend friend = new UserFriend();

				// 用户名
				friend.setUfName(data.get((int) id).get("username") != null ? data
						.get((int) id).get("username").toString()
						: "");

				// 头像
				friend.setUfPhoto(data.get((int) id).get("userimg") != null ? data
						.get((int) id).get("userimg").toString()
						: "");

				// UID
				friend.setUfID(data.get((int) id).get("uid").toString());

				Bundle bundleUF = new Bundle();

				bundleUF.putSerializable("com.hichat.UserFriend", friend);

				chatIntent.putExtras(bundleUF);

				startActivity(chatIntent);

			}
		});

	}

	/*
	 * ViewHolder
	 */
	private static class ViewHolder {

		TextView textViewName;

		ImageView imageViewPhoto;

		TextView textViewKmTime;

		TextView textViewContent;

		TextView textViewSex;

		Button btnPhoto;

		TextView textViewTime;
	}

	private String str_km_distance = "";
	private String str_time = "";

	@Override
	public View bindView(PullToRefreshListAdapter adapter, final int position,
			View convertView, ViewGroup parent) {

		ViewHolder viewHolder = null;

		if (convertView == null) {
			convertView = adapter.getLayoutInflater().inflate(
					R.layout.item_nearby, null);
			viewHolder = new ViewHolder();

			viewHolder.imageViewPhoto = (ImageView) convertView
					.findViewById(R.id.item_n_photo);

			viewHolder.textViewContent = (TextView) convertView
					.findViewById(R.id.item_n_content);

			viewHolder.textViewKmTime = (TextView) convertView
					.findViewById(R.id.item_n_km_time);

			viewHolder.textViewSex = (TextView) convertView
					.findViewById(R.id.item_n_sex);

			viewHolder.textViewName = (TextView) convertView
					.findViewById(R.id.item_n_name);

			viewHolder.btnPhoto = (Button) convertView
					.findViewById(R.id.item_n_btn);

			viewHolder.textViewTime = (TextView) convertView
					.findViewById(R.id.item_n_time);

			convertView.setTag(viewHolder);

		} else {
			viewHolder = (ViewHolder) convertView.getTag();
		}

		viewHolder.textViewName
				.setText(data.get(position).get("username") != null ? data
						.get(position).get("username").toString() : "");

		str_km_distance = tools.beautifulDistance(data.get(position)
				.get("juli") != null ? data.get(position).get("juli")
				.toString() : "0");

		str_time = data.get(position).get("lastdatetime") != null ? tools
				.beautifulDateTime(data.get(position).get("lastdatetime")
						.toString()) : "";

		viewHolder.textViewKmTime.setText(str_km_distance);

		viewHolder.textViewTime.setText(str_time);

		viewHolder.textViewContent
				.setText(data.get(position).get("sign") != null ? data
						.get(position).get("sign").toString() : "");
		//

		if (data.get(position).get("usex") != null) {

			viewHolder.textViewSex
					.setBackgroundResource(tools.getSexBackground(data
							.get(position).get("usex").toString()));

			viewHolder.textViewSex.setGravity(Gravity.CENTER_VERTICAL);
			viewHolder.textViewSex.setPadding(40, 2, 5, 0);

		}

		viewHolder.textViewSex
				.setText(data.get(position).get("age").toString());

		String photoString = str_defaultPhoto;

		if (data.get(position).get("userimg") != null) {

			photoString = this.getResources().getString(R.string.URL)
					+ data.get(position).get("userimg").toString();

		}

		viewHolder.btnPhoto.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO 自动生成的方法存根

				Intent intent = new Intent();
				intent.setClass(getActivity(), ActivityPersonal.class);
				Bundle theUID = new Bundle();
				theUID.putString("uid", data.get(position).get("uid")
						.toString());
				intent.putExtras(theUID);
				startActivity(intent);
			}
		});

		imageLoader.displayImage(photoString, viewHolder.imageViewPhoto,
				options);
		// TODO 自动生成的方法存根
		return convertView;
	}

	@Override
	public void requestFinish() {
		mPullRefreshListView.setPullToRefreshListDelegate(this);
		mPullRefreshListView.setDataSource(data);
		mPullRefreshListView.setAdapter(null);
		mPullRefreshListView.getAdapterEx().notifyDataSetChanged();
		handler2.sendEmptyMessageDelayed(1, 500);

	}

	private OnClickListener btnClick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO 自动生成的方法存根
			Intent intent = new Intent();

			intent.setClass(view.getContext(), ActivityNearbySearch.class);

			startActivityForResult(intent, SHOW_ACTIVITY_SEARCH);
		}
	};

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) {
		case SHOW_ACTIVITY_SEARCH:
			str_ageMax = data.getStringExtra("str_ageMax");
			str_appearTime = data.getStringExtra("str_appearTime");
			str_sex = data.getStringExtra("str_sex");
			str_ageMin = data.getStringExtra("str_ageMin");
			list.clear();
			page = 1;
			// handler.sendEmptyMessageDelayed(1, 500);
			requestNetworkData();

			break;

		}
	}

	@Override
	protected void requestError() {
		// TODO 自动生成的方法存根
		handler2.sendEmptyMessageDelayed(1, 500);
		Toast.makeText(getActivity(), "网络连接错误", Toast.LENGTH_SHORT).show();
	};

	Handler handler2 = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO 自动生成的方法存根
			super.handleMessage(msg);
			mPullRefreshListView.onRefreshComplete();
		}
	};

	@Override
	public void XMPPConnectionStateListener(XMPPConnectionState args) {
		// TODO 自动生成的方法存根

	}
}
